package ro.upt.dcda.pricezone.s1.requests;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import ro.upt.dcda.pricezone.common.ConnectionFactory;
import ro.upt.dcda.pricezone.s1.pojo.LoggedUser;
import ro.upt.dcda.pricezone.s1.pojo.User;

public class LoginRequest {

	private User user;
	private String sid;

	/**
	 * 
	 * @param usermail
	 * @param password
	 * @param platform_id
	 *            0 for web, 1 for android
	 * @return
	 */
	public boolean work(String usermail, String password, int platform_id) {
		Session session = ConnectionFactory.getFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Query query = session
					.createQuery("from User where email=:email and password=:password");
			query.setParameter("email", usermail);
			query.setParameter("password", password);
			List<?> list = query.list();
			if (list.size() != 1) {
				return false;
			}
			user = (User) list.get(0);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return false;
		} finally {
			session.close();
		}
		login(platform_id);
		return true;
	}

	public User getUser() {
		return user;
	}

	public String getSid() {
		return sid;
	}

	private void login(int platform_id) {
		Session session = ConnectionFactory.getFactory().openSession();
		Transaction tx = null;
		try {
			System.out.println("Trying to login user");
			tx = session.beginTransaction();
			Query q = session
					.createQuery("delete LoggedUser where user_id = :user_id and platform_id=:platform_id");
			q.setParameter("user_id", user.getId());
			q.setParameter("platform_id", platform_id);
			q.executeUpdate();
			LoggedUser loggedUser = new LoggedUser(user.getId(), UUID
					.randomUUID().toString(), platform_id, new Date());
			for (int i = 0; i < 10; i++) {
				try {
					session.save(loggedUser);
					sid = loggedUser.getSid();
					continue;
				} catch (HibernateException e) {
					e.printStackTrace();
					if (i == 9) {
						throw e;
					}
					loggedUser.setSid(UUID.randomUUID().toString());
				}
			}
			tx.commit();
			System.out.println("user login succesful");
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
